<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use app\common\controller\Api;
use app\common\model\UserWithdrawalLog;
use app\common\model\User;
use think\Cache;

class Index extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $layout = '';
    
    public function index()
    {
        return $this->view->fetch();
    }


    public function meishikaiLogin()
    {
        $MeishikaiService = new \services\MeishikaiService();
        $meishikai = Db::name('meishikai')->where('id',1)->find();
        if ($meishikai) {
            // if ($meishikai['expire_time']-time()<=86400) {
                $res = $MeishikaiService->userLogin();
                $decode = json_decode($res,1);
                if (isset($decode['Content']['Token']) && $decode['Content']['Token']) {
                    Db::name('meishikai')->where('id',1)->update([
                        'content' => $res,
                        'token' => $decode['Content']['Token'],
                        'update_dt' => date('Y-m-d H:i:s'),
                        // 'expire_time' => strtotime($decode['Content']['DatExpired']),
                        'expire_time' => time()+518400,
                    ]);
                }
            // }
        } else {
            $res = $MeishikaiService->userLogin();
            $decode = json_decode($res,1);
            if (isset($decode['Content']['Token']) && $decode['Content']['Token']) {
                Db::name('meishikai')->insert([
                    'content' => $res,
                    'token' => $decode['Content']['Token'],
                    'update_dt' => date('Y-m-d H:i:s'),
                    // 'expire_time' => strtotime($decode['Content']['DatExpired']),
                    'expire_time' => time()+518400,
                ]);
            }
        }
    }


    // public function isAuth()
    // {
    //     $MeishikaiService = new \services\MeishikaiService();
    //     $meishikai = Db::name('meishikai')->where('id',1)->find();
    //     $shop_authorize = Db::name('shop_authorize')->where(['is_success'=>0])->select();
    //     Db::startTrans();
    //     try {
    //         if ($shop_authorize) {
    //             $pshopid = [];
    //             foreach ($shop_authorize as $key => $value) {
    //                 $pshopid[] = $value['pshopid'];
    //             }
    //             $res = $MeishikaiService->getShopList($meishikai['token'],1,'美团',$pshopid);
    //             $decode = json_decode($res,1);
    //             $pshopid = [];
    //             $shop_no = [];
    //             if (isset($decode['Content']['RecordList'])) {
    //                 foreach ($decode['Content']['RecordList'] as $v) {
    //                     if ($v['IsEffective']===true) {
    //                         $pshopid[] = $v['PShopId'];
    //                     }
    //                 }
    //             }
    //             $shop_authorizes = Db::name('shop_authorize')->where(['pshopid'=>['in',$pshopid]])->select();
    //             Db::name('shop_authorize')->where(['pshopid'=>['in',$pshopid]])->update(['is_success'=>1]);
    //             foreach ($shop_authorizes as $vv) {
    //                 $shop_no[] = $vv['shop_no'];
    //             }
    //             Db::name('shop')->where(['shop_no'=>['in',$shop_no]])->update(['is_auth'=>1]);
    //             Db::commit();
    //         }
    //     } catch (\Exception $e) {
    //         Db::rollback();
    //     }
    // }


    public function getPshopid()
    {
        $MeishikaiService = new \services\MeishikaiService();
        $meishikai = Db::name('meishikai')->where('id',1)->find();
        for ($i=1; $i < 10000; $i++) { 
            $res = $MeishikaiService->getShopList($meishikai['token'],$i,'美团',[]);
            $decode = json_decode($res,1);
            $pshopid = [];
            $shop_no = [];
            Db::startTrans();
            try {
                if (isset($decode['Content']['RecordList'])) {
                    foreach ($decode['Content']['RecordList'] as $v) {
                        $shop_authorizes = Db::name('shop_authorize')->where(['username'=>$v['PUserId']])->find();
                        if ($v['IsEffective']===true && !$shop_authorizes['is_success']) {
                            Db::name('shop_authorize')->where(['id'=>$shop_authorizes['id']])->update([
                                'is_success'=>1,
                                'pshopid' => $v['PShopId'],
                                'shop_name' => $v['ShopName'],
                            ]);
                            Db::name('shop')->where(['shop_no'=>$shop_authorizes['shop_no']])->update(['is_auth'=>1,'shop_name'=>$v['ShopName']]);

                            $phone = Db::name('shop')->where(['shop_no'=>$shop_authorizes['shop_no']])->value('phone');
                            // Db::name('shop')->where(['phone'=>$phone,'is_auth'=>0])->update(['is_auth'=>1]);
                        }
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                echo 'fail'.$i;exit;
            }
            if (count($decode['Content']['RecordList'])==0) break;
        }
        echo 'success';exit;
    }

    // 给用户发红包
    public function distributeBeans()
    {
        $play_order_no = input('no','');
        $order = Db::name('play_order')->where('play_order_no',$play_order_no)->find();
        if (!$order) $this->error('订单不存在');
        $user = (new \app\common\model\User())->where(['id' => $order['user_id']])->find();
        if (empty($user) || $user->status != 'normal') $this->error('账户异常');
        if ($order['actual_rebate_amt'] <= 0 || $order['actual_rebate_amt'] > $user->beans || $user->beans<0) $this->error('吃豆不足');
        if (Db::name('user_beans_log')->where(['user_id'=>$order['user_id'],'log_type'=>2,'tran_no'=>$play_order_no])->count()) {
            $this->error('已发放返利');
        }
        $after = $user->beans-$order['actual_rebate_amt'];
        $data = [
            'log_mod' => 'wechat',
            'card_no' => '',
            'real_name' => '',
            'withdrawal_no' => $this->generateNo(['biz_tag'=>'withdrawal_no','len'=>12,'int_prefix'=>5]),
            'user_id' => $order['user_id'],
            'log_type' => 1,
            'wallet' => $order['actual_rebate_amt'],
            'before_wallet' => $user->beans,
            'after_wallet' => $after,
            'with_time' => time(),
            'with_desc' => '',
            'log_status' => 0,
            'is_merchant' => 2
        ];
        $log = UserWithdrawalLog::create($data);
        // 获取公钥
        $WxwithdrawalService = new \services\WxwithdrawalService();
        $publickey = Cache::get('publickey');
        if (!$publickey) {
            // 获取微信证书
            $res = $WxwithdrawalService->certificates();
            $certificates = json_decode($res,1);
            $Aes = new \fast\AesUtil(config('msxgzh.mch_key'));
            $associatedData = $certificates['data'][0]['encrypt_certificate']['associated_data'];
            $nonceStr = $certificates['data'][0]['encrypt_certificate']['nonce'];
            $ciphertext = $certificates['data'][0]['encrypt_certificate']['ciphertext'];
            // 解析公钥
            $publickey = $Aes->decryptToString($associatedData, $nonceStr, $ciphertext); 
            Cache::set('publickey',$publickey,86400);
        }
        $openid = User::where('id',$order['user_id'])->value('openid');
        $appid=config('msxgzh.appid');
        if (!$openid) {
            $this->error('无法获得授权，请联系客服处理！');
        }
        //请求参数,大于0.3要传姓名
        // if ($log['wallet']<0.3 || $user['real_name']=='SHEE KAI YING' || $user['real_name']=='JCHANGLOCK') {
            $data = [
                'appid'=>$appid,
                'out_batch_no'=>strval($log['withdrawal_no']),
                'batch_name' => '美食秀提现',
                'batch_remark' => '美食秀提现',
                'total_amount' => intval(strval($log['wallet']*100)),
                'total_num' => 1,
                'transfer_detail_list'=>[[
                    'out_detail_no' => strval($log['withdrawal_no']),
                    'transfer_amount'=>intval(strval($log['wallet']*100)),
                    'transfer_remark'=>'美食秀提现',
                    'openid' => $openid,
                ]],
                'notify_url' => config('domain').'/index/index/txNotify'
            ];
        // } else {
        //     $data = [
        //         'appid'=>$appid,
        //         'out_batch_no'=>strval($log['withdrawal_no']),
        //         'batch_name' => '美食秀提现',
        //         'batch_remark' => '美食秀提现',
        //         'total_amount' => intval(strval($log['wallet']*100)),
        //         'total_num' => 1,
        //         'transfer_detail_list'=>[[
        //             'out_detail_no' => strval($log['withdrawal_no']),
        //             'transfer_amount'=>intval(strval($log['wallet']*100)),
        //             'transfer_remark'=>'美食秀提现',
        //             'openid' => $openid,
        //             'user_name' => $WxwithdrawalService->getEncrypt($user['real_name'],$publickey),
        //         ]],
        //         'notify_url' => config('domain').'/index/index/txNotify'
        //     ];
        // }
        $res = $WxwithdrawalService->transfer($data);
        // $res = [
        //     'batch_id' => '131000500055107114193172025010750387302020',
        //     'batch_status' => 'ACCEPTED',
        //     'create_time' => '2025-01-07T19:04:04+08:00',
        //     'out_batch_no' => '518976302400'
        // ];
        Db::startTrans();
        try {
            if(!isset($res['create_time'])) {//批次受理失败
                Db::rollback();
                $this->error('零钱转账失败');
            }
            $beans = -1*$order['actual_rebate_amt'];
            (new User())->beans($beans, $order['user_id'], '吃豆提现', $play_order_no);
            // 审核通过
            $result = $log->allowField(true)->save([
                'log_status' => 1,
                'handel_admin_id' => $user->id,
                'handel_time' => time(),
                'batch_id' => $res['batch_id'],
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('零钱转账失败');
        }
        $this->success('success');
    }

    // 提现回调
    public function txNotify()
    {
        $params = $this->request->param();
        // $res = '{"id":"d0fdf54b-6ba6-5c86-a8c4-3689a0b104ca","create_time":"2024-05-18T14:02:05+08:00","resource_type":"encrypt-resource","event_type":"MCHTRANSFER.BATCH.FINISHED","summary":"\u5546\u5bb6\u8f6c\u8d26\u6279\u6b21\u5b8c\u6210\u901a\u77e5","resource":{"original_type":"mch_payment","algorithm":"AEAD_AES_256_GCM","ciphertext":"ajBUlvD6cttKvD1VhsTCDn3\/IN5VAdkNu1pOiqBPckxjzr\/hzKkuDYlidGxYSnmnHkGfgPLRicoRkDr7cjRAOJfMDQ9IS8x2Fzgytoq9Y1ps7A8+99gxR+EfzJnCpnPMKXa821ETEUcGuRhiIMi9gP4nJUPS7AiOewXkcX0J\/syUWIJEZRo2oaF5MhmIs5ufS9A2kewowx4el\/1q4+nAJ41T\/5494EGp9bqVMjs45NOM97cQV\/Ja4PuKDOszt8GzGmgpUuf5xtFK6SA6F1noj6AejjC5vu6SRa5aulgzB7NwIb9MQs+a\/eZ+dOixc0ixa1wZIM5BORPRgkLbgc4\/RyurdTg+UNJmALn1Vm\/VuU0gTNHueZ7NzSdH+07n1ISLve1Ip5zdzSs6ZmD9fljcGUHSxSoOD2Pwng==","associated_data":"mch_payment","nonce":"W0pQlzafu0QN"}}';
        // $params = json_decode($res,1);
        $key = config('msxgzh.mch_key');
        // $decrypted = '{"out_batch_no":"595130427277","batch_id":"131000701058501691086842024022972600665912","batch_status":"FINISHED","total_num":1,"total_amount":100,"success_amount":100,"success_num":1,"fail_amount":0,"fail_num":0,"mch_id":"1644161646","update_time":"2024-05-17T13:52:36+08:00","mchid":"1644161646"}';
        $Aes = new \fast\AesUtil($key);
        $associatedData = $params['resource']['associated_data'];
        $nonceStr = $params['resource']['nonce'];
        $ciphertext = $params['resource']['ciphertext'];
        // 解析公钥
        $decrypted = $Aes->decryptToString($associatedData, $nonceStr, $ciphertext);
        \think\Log::write('转账回调'.$decrypted);
        // $decrypted = sodium_crypto_aead_aes256gcm_decrypt(base64_decode($params['resource']['ciphertext']),$params['resource']['associated_data'],$params['resource']['nonce'],$key);
        $decrypted = json_decode($decrypted,1);
        Db::startTrans();
        try {
            if (!$decrypted['fail_amount'] && !$decrypted['fail_num']) {
            } else {
                $user_withdrawal_log = Db::name('user_withdrawal_log')->where(['withdrawal_no'=>$decrypted['out_batch_no']])->find();
                // 审核不通过，返还用户金额
                Db::name('user_withdrawal_log')->where(['withdrawal_no'=>$decrypted['out_batch_no']])->update(['log_status'=>-1,'update_dt'=>date('Y-m-d H:i:s',strtotime($decrypted['update_time'])),'handel_desc'=>'提现失败（真实姓名与微信收款账户不符）']);
                if ($user_withdrawal_log['is_merchant']==2) {
                    $beans = $user_withdrawal_log['wallet'];
                    $res = (new User())->beans($beans, $user_withdrawal_log['user_id'], '提现失败（真实姓名与微信收款账户不符）', $user_withdrawal_log['id']);
                } elseif ($user_withdrawal_log['is_merchant']==0) {
                    //冻结金额扣除
                    $money = $user_withdrawal_log['wallet'];
                    User::money($money, $user_withdrawal_log['user_id'], '提现失败（真实姓名与微信收款账户不符）', $user_withdrawal_log['id'], 1);
                } elseif ($user_withdrawal_log['is_merchant']==3) {
                    //冻结金额扣除
                    $money = $user_withdrawal_log['wallet'];
                    User::money($money, $user_withdrawal_log['user_id'], '提现失败（真实姓名与微信收款账户不符）', $user_withdrawal_log['id'], 1);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

}
